package com.carl.guli.controller;

import com.carl.guli.common.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Arrays;
import java.util.Calendar;


/**
 * Created by youzm on 2017/3/15.
 */
@Controller
@RequestMapping("/common")
public class CommonController extends BaseController {

    @Value("${ftp.directory}")
    private String ftpPath;

    @Value("${ftp.pic}")
    private String ftpPic;

    @Value("${ftp.download}")
    private String ftpDownload;

    @RequestMapping("/upload")
    public void uploadImg(@RequestParam("wangEditorH5File") CommonsMultipartFile[] myFileName, HttpServletRequest request, HttpServletResponse response) throws Exception{
        // 文件类型限制
        CommonsMultipartFile mf = myFileName[0];
        File file = null;
        String[] allowedType = { "image/bmp", "image/gif", "image/jpeg", "image/png" };

        boolean allowed = Arrays.asList(allowedType).contains(mf.getContentType());
        if (!allowed) {
            response.getWriter().write("error|不支持的类型");
            return;
        }
        // 图片大小限制
        if (mf.getSize() > 5 * 1024 * 1024) {
            response.getWriter().write("error|图片大小不能超过5M");
            return;
        }


        if (!mf.isEmpty()) {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            // 生成指定路径和指定名称的文件
            String path = ftpPath + ftpPic + "/" + year + "" + month;

            file = FileUploadUtil.getFileByPath(path, mf);
            // 将上传的文件写入新建的文件中
            mf.getFileItem().write(file);
            // 文件名
            String fileName = ftpPic + "/" + year + "" + month + "/" + file.getName() + ";";
            response.getWriter().write(ftpDownload + fileName);
        }
    }

}
